package com.uniriho.lxr0811_7300_bl.ui.activity;


import static com.uniriho.lxr0811_7300_bl.base.Constant.BLUE_TOOTH_DIALOG;
import static com.uniriho.lxr0811_7300_bl.base.Constant.BLUE_TOOTH_SUCCESS;
import static com.uniriho.lxr0811_7300_bl.base.Constant.BLUE_TOOTH_TOAST;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;


import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.snackbar.Snackbar;
import com.uniriho.lxr0811_7300_bl.R;
import com.uniriho.lxr0811_7300_bl.adapter.ItemBtListAdapter;
import com.uniriho.lxr0811_7300_bl.base.Constant;
import com.uniriho.lxr0811_7300_bl.ble.BlueToothInterface;
import com.uniriho.lxr0811_7300_bl.ble.BluetoothChatService;
import com.uniriho.lxr0811_7300_bl.ble.BluetoothStateBroadcastReceive;
import com.uniriho.lxr0811_7300_bl.ble.BluetoothUtil;
import com.uniriho.lxr0811_7300_bl.domain.BlueToothBean;
import com.uniriho.lxr0811_7300_bl.utils.XPermissionUtil;

import java.util.ArrayList;
import java.util.List;

public class BluActivity extends Activity implements AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {
    public static final int BLUE_TOOTH_DISCONNECT = 0x666;
    private BluetoothUtil bluetoothUtil;
    private BluetoothStateBroadcastReceive broadcastReceive;
    private SwipeRefreshLayout layoutSwipeRefresh;
    private ListView lvBtList;
    private List<BlueToothBean> list;
    private ItemBtListAdapter adapter;
    private LinearLayout layoutHide;
    private ProgressDialog progressDialog;
    private BluetoothChatService mBluetoothChatService;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //正在连接
                case BLUE_TOOTH_DIALOG:
                    Toast.makeText(BluActivity.this, "正在连接", Toast.LENGTH_SHORT).show();
//                    showProgressDialog((String) msg.obj);
                    break;
                //连接失败
                case BLUE_TOOTH_TOAST:
                    Toast.makeText(BluActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
//                    dismissProgressDialog();
//                    Snackbar.make(getView(), (String) msg.obj, Snackbar.LENGTH_LONG).show();
                    break;
                //连接成功
                case BLUE_TOOTH_SUCCESS:
                    Toast.makeText(BluActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    final Intent intent = new Intent(BluActivity.this, HomeActivity.class);
                    startActivity(intent);
                    break;

                case BLUE_TOOTH_DISCONNECT:
                    Toast.makeText(BluActivity.this, "蓝牙已断开", Toast.LENGTH_SHORT).show();
                    Constant.BluConnectState =false;
            }
        }
    };
    private BlueToothInterface blueToothInterface = new BlueToothInterface() {
        @SuppressLint("MissingPermission")
        @Override
        public void getBlueToothDevices(BluetoothDevice device) {
            @SuppressLint("MissingPermission") BlueToothBean blueToothBean = new BlueToothBean(device.getName(), device.getAddress());
            if (device.getName() != null && device.getAddress() != null) {
                int k = 0;
                for (BlueToothBean i : list)
                    if (i.getMac().equals(blueToothBean.getMac()))
                        k++;
                if (k == 0) {
                    list.add(blueToothBean);
                    adapter.notifyDataSetChanged();
                }
            }
        }

        @Override
        public void getConnectedBlueToothDevices(BluetoothDevice device) {
            Log.i("zjh-ConnectedBlue", "连接成功");
            Message message = handler.obtainMessage();
            message.what = BLUE_TOOTH_SUCCESS;
            message.obj = "连接成功";
            handler.sendMessage(message);
            Constant.BluConnectState = false;
            update();
        }

        @Override
        public void getDisConnectedBlueToothDevices(BluetoothDevice device) {
            Log.i("zjh-DisConnected", "断开连接");
            Message message = handler.obtainMessage();
            message.what = BLUE_TOOTH_DISCONNECT;
            message.obj = "断开连接";
            handler.sendMessage(message);
            Constant.BluConnectState = false;
            update();
        }

        @Override
        public void searchFinish() {
            layoutSwipeRefresh.setRefreshing(false);
        }

        @Override
        public void open() {
            mBluetoothChatService = BluetoothChatService.getInstance(handler);
//            mBluetoothChatService.start();
            update();
        }

        @Override
        public void disable() {
            mBluetoothChatService.stop();
            update();
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluactivity);

        initView();
        initData();
        initEvent();
    }

    private void initEvent() {

    }

    private void initData() {
        XPermissionUtil.requestPermissions(this, 1,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.BLUETOOTH,
                        Manifest.permission.BLUETOOTH_ADMIN,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION},
                new XPermissionUtil.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        //权限获取成功
                    }

                    @Override
                    public void onPermissionDenied() {
                        //权限获取失败
//                        Snackbar.make(bottomNavigationView, "请手动到设置界面给予相关权限", Snackbar.LENGTH_LONG).show();
                        Toast.makeText(BluActivity.this, "权限获取失败，请授权", Toast.LENGTH_SHORT).show();
                    }
                });
        bluetoothUtil = new BluetoothUtil(this);
        list = new ArrayList<>();
        adapter = new ItemBtListAdapter(list, this);
        lvBtList.setAdapter(adapter);
        lvBtList.setOnItemClickListener(this);
        update();
        registerBluetoothReceiver();
    }

    private void initView() {
        layoutSwipeRefresh = findViewById(R.id.layout_swipe_refresh);
        lvBtList = findViewById(R.id.lv_bt_list);
        layoutHide = findViewById(R.id.layout_hide);
        layoutSwipeRefresh.setOnRefreshListener(this);
    }

    private void registerBluetoothReceiver() {
        Log.i("zjh", "蓝牙广播监听启动");
        if (broadcastReceive == null) {
            broadcastReceive = new BluetoothStateBroadcastReceive(blueToothInterface);
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
        intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");
        this.registerReceiver(broadcastReceive, intentFilter);
    }

    private void unregisterBluetoothReceiver() {
        Log.i("zjh", "蓝牙广播监听关闭");
        if (broadcastReceive != null) {
            this.unregisterReceiver(broadcastReceive);
            broadcastReceive = null;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        BluetoothDevice bluetoothDevice = bluetoothUtil.getBluetoothDevice(list.get(position).getMac());
        if (bluetoothDevice != null) {
            mBluetoothChatService.connectDevice(bluetoothDevice);
        }
    }

    private void update() {

        list.clear();
        if (bluetoothUtil.isBluetoothEnable()) {
            layoutHide.setVisibility(View.INVISIBLE);
            list.addAll(bluetoothUtil.getDevicesList());
            bluetoothUtil.startDiscovery();
            layoutSwipeRefresh.setRefreshing(true);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    bluetoothUtil.close();
                    layoutSwipeRefresh.setRefreshing(false);
                }
            },5000);
        } else {
            layoutHide.setVisibility(View.VISIBLE);
            layoutSwipeRefresh.setRefreshing(false);
        }
        adapter.notifyDataSetChanged();
        if (bluetoothUtil.isBluetoothEnable()) {
            mBluetoothChatService = BluetoothChatService.getInstance(handler);
//            mBluetoothChatService.start();
        }

    }
    @Override
    public void onRefresh() {
        update();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterBluetoothReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mBluetoothChatService.disConnect();
    }
}
